import { ChangeEvent, useContext, useEffect, useState } from 'react';
import { useForm, useWatch } from 'react-hook-form';
import { useTranslation } from 'react-i18next';
import { useDispatch, useSelector } from 'react-redux';
import { useNavigate } from 'react-router-dom';
import Alert from 'src/component/Alert';
import AutoCompleteOption from 'src/component/AutoCompleteOption';
import BackButton from 'src/component/BackButton';
import Button from 'src/component/Button';
import Checkbox from 'src/component/Checkbox';
import Form from 'src/component/Form';
import FormAutoComplete from 'src/component/FormAutoComplete';
import FormInput from 'src/component/FormInput';
import FormNumberInput from 'src/component/FormNumberInput';
import FormSelect from 'src/component/FormSelect';
import SelectOption from 'src/component/SelectOption';
import { Ui } from 'src/constant/Env';
import { Severity } from 'src/constant/Notification';
import { Page } from 'src/constant/Page';
import { ThemeContext } from 'src/context/ThemeContext';
import useQuery from 'src/hook/useQuery';
// import IcCheck from 'src/image/ic-check.svg';
// import { PostWithdrawalResponse, PostWithdrawalsPreviewResponse } from 'src/model/Api';
// import { Contact } from 'src/model/Contact';
// import { WithdrawalForm } from 'src/model/Form';
import { RootState } from 'src/redux/store';
import { openSnackbar } from 'src/redux/uiSlice';
// import { createWithdrawal, getContactList, previewWithdrawal } from 'src/service/propertyService';
import { getMyAddress, addWithdraw } from 'src/service/moneyService'
import { bn, bnFixed, bnFormat } from 'src/util/bigNumber';
// import NewAddressModal from './component/NewAddressModal';
// import VerifyModal from './component/VerifyModal';
import style from './Withdrawal.module.scss';

type PostWithdrawalResponse = any
type PostWithdrawalsPreviewResponse = any
type Contact = any
type Query = any

type WithdrawalForm = {
  coin?: string;
  network?: string;
  address?: string;
  amount?: string;
  note?: string;
  code?: string;
};

const Withdrawal = () => {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const dispatch = useDispatch();
  const { IcRecord, IcForward } = useContext(ThemeContext).image;
  const query = useQuery<Query>();
  const { crypto } = useSelector((rootState: RootState) => rootState.coin);
  const { accountInfo } = useSelector((rootState: RootState) => rootState.auth);
  const { baseDataInfo } = useSelector((rootState: RootState) => rootState.basedata);
  const [coinDecimal, setCoinDecimal] = useState<number>(0);
  const [contactList, setContactList] = useState<Contact[]>([]);
  const [isSaveAddressModalOpen, setSaveAddressModalOpen] = useState<boolean>(false);
  const [verifyModalOpen, setVerifyModalOpen] = useState<boolean>(false);
  const methods = useForm<WithdrawalForm>();
  const formData = useWatch({ control: methods.control });
  const [withdrawalData, setWithdrawalData] = useState<PostWithdrawalResponse>();
  const [previewTask, setPreviewTask] = useState<number>();
  const [previewData, setPreviewData] = useState<PostWithdrawalsPreviewResponse>();
  const [checkboxLabel, setCheckboxLabel] = useState<string>();
  const [refresh, setRefresh] = useState<boolean>(false);
  const [isDisable, setIsDisable] = useState<boolean>(false);
  const token = localStorage.getItem("token")

  useEffect(() => {
    if (crypto.length === 0) return;
    // getContactList()
    //   .then((res) => setContactList(res))
    //   .catch((e) => dispatch(openSnackbar({ message: e, severity: 'alert' })));
  }, [crypto, refresh]);

  useEffect(() => {
    if (baseDataInfo?.FSxf || accountInfo?.FCoin) return;
    // setDaseInfo({
    //   sxf: baseDataInfo?.FSxf,
    //   ye: accountInfo?.FCoin
    // })
  }, [baseDataInfo?.FSxf, accountInfo?.FCoin]);

  useEffect(() => {
    if (!accountInfo?.FID) return
    getMyAddress({
      uMail: accountInfo?.FMail,
      FUserID: accountInfo?.FID,
      token: token
    }).then(res => {
      if (res.success) {
        setContactList(res.list)
      }
    })
  }, [accountInfo])

  // useEffect(() => {
  //   if (accountInfo === undefined) return;
  //   // if (accountInfo.otpActivated !== true) navigate(Page.Property);
  // }, [accountInfo]);


  useEffect(() => {
    setPreviewData(undefined);
    if (!formData.coin || !formData.address || formData.address.length === 0) return;

    if (previewTask) window.clearTimeout(previewTask);

    const requestData = {
      coin: formData.coin,
      network: formData.network,
      address: formData.address,
    };

    const task = window.setTimeout(() => {
      //   previewWithdrawal(requestData)
      //     .then((res) => {
      //       setPreviewData(res);
      //       setPreviewTask(undefined);
      //     })
      //     .catch((e) => dispatch(openSnackbar({ message: e, severity: 'alert' })));
    }, 500);

    setPreviewTask(task);

    return () => window.clearTimeout(task);
  }, [formData.address]);

  useEffect(() => {
    setIsDisable(false);
    if (!formData.coin || !formData.address || !formData.code) return;
    setIsDisable(true);

  }, [formData]);

  useEffect(() => {
    // if (crypto.length === 0) return;

    // let currentCoin = 'usdt';
    // if (query.coinId && crypto.map((v) => v.id).includes(query.coinId.toLowerCase())) {
    //   methods.setValue('coin', query.coinId.toLowerCase());
    //   currentCoin = query.coinId.toLowerCase();
    // } else methods.setValue('coin', 'usdt');

    // const currentCrypto = crypto.find((v) => v.id === currentCoin);
    // if (currentCrypto?.networks.length === 1 && currentCrypto.networks[0].network === '')
    //   methods.setValue('network', '');
    // else if (
    //   query.network &&
    //   currentCrypto?.networks.map((v) => v.network).includes(query.network.toLowerCase())
    // )
    //   methods.setValue('network', query.network.toLowerCase());
    // else methods.setValue('network', 'trc20');

    // setCoinDecimal(crypto.find((v) => v.id === currentCoin)?.decimal ?? 0);
  }, [crypto, query]);

  useEffect(() => {
    const { amount, address } = methods.getValues();

    // setCheckboxLabel(
    //   contactList?.find((v) => v.address === address && v.coin === formData.coin)?.label,
    // );

    if (previewData === undefined) return;

    // if (!previewData.isAddressValid)
    //   methods.setError('address', { message: t('withdrawal.desc.addressInvalidate') });
    // else methods.clearErrors('address');

    // if (bn(amount).gt(bn(previewData.max)))
    //   methods.setError('amount', { message: t('withdrawal.desc.amountGreaterThan') });
    // else methods.clearErrors('amount');
  }, [formData, previewData, contactList, t]);

  const onCoinChange = (coin: string) => {
    // methods.setValue('coin', coin);
    // if (coin === 'usdt') methods.setValue('network', 'trc20');
    // else methods.setValue('network', '');
  };

  const onSubmit = (data: WithdrawalForm) => {
    addWithdraw({
      token: token,
      FUserID: accountInfo?.FID,
      FUserMail: accountInfo?.FMail,
      FType: data.coin,
      FNet: data.network,
      FAddress: data.address,
      FQuantity: data.amount,
      FSxf: baseDataInfo?.FSxf,
      FNote: data.note,
      FGoogle: data.code,
    }).then(res => {
      if (res.success) {
        navigate("/property/records?type=withdrawal")
        dispatch(openSnackbar({ message: res.message }))
      } else {
        dispatch(openSnackbar({ message: res.message, severity: 'alert' }))
      }
    })
    // createWithdrawal(
    //   {
    //     coin: data.coin,
    //     network: data.network,
    //     address: data.address,
    //     amount: Number.parseFloat(data.amount),
    //     note: data.note.length > 0 ? data.note : undefined,
    //   },
    //   data.code,
    // )
    //   .then((res) => {
    //     setWithdrawalData(res);
    //     setVerifyModalOpen(true);
    //   })
    //   .catch((e) => dispatch(openSnackbar({ message: e, severity: 'alert' })));
  };

  return (
    <div>
      <BackButton />
      <div className={style.headingBlock}>
        <div className={style.heading}>提领</div>
        {(
          <Button
            appearance="text"
            className={style.recordButton}
            onClick={() => navigate(`${Page.Record}?type=withdrawal`)}
          >
            <img src={IcRecord} />
            充值与提领纪录
          </Button>
        )}
      </div>
      <Form methods={methods} onSubmit={onSubmit}>
        <div className={style.content}>
          <div className={style.coinSelectBlock}>
            <div className={style.coinSelect}>
              <FormSelect
                name="coin"
                label="币别"
                defaultValue='USDT'
                // onChange={onCoinChange}
                asterisked
              >
                <SelectOption value="USDT">
                  USDT
                </SelectOption>
              </FormSelect>
            </div>
            <div className={style.networkSelect}>
              <FormSelect
                name="network"
                label="选择网路"
                defaultValue='TRC20'
                asterisked>
                <SelectOption value="TRC20">
                  TRC20
                </SelectOption>
              </FormSelect>
            </div>
          </div>
          <div className={style.addressBlock}>
            <div className={style.addressInput}>
              <FormAutoComplete
                name="address"
                label="地址"
                maxLength={256}
                placeholder="接收者的USTD地址"
                required
                asterisked
              >
                {contactList.map((v) => (
                  <AutoCompleteOption key={v.FID} value={v.FAddress}>
                    <div className={style.contact}>
                      <div className={style.network}>{v.FTag}</div>
                      <div className={style.address}>{v.FAddress}</div>
                    </div>
                  </AutoCompleteOption>
                ))}
              </FormAutoComplete>
            </div>
            <div className={style.saveAddress}>
              {/* {checkboxLabel !== undefined ? (
                  <div className={style.savedAddress}>
                    <img src={"IcCheck"} />
                    <div>{checkboxLabel}</div>
                  </div>
                ) : (
                  <Checkbox
                    label="储存地址"
                    disabled={!previewData?.isAddressValid}
                    onChange={(event: ChangeEvent<HTMLInputElement>) =>
                      setSaveAddressModalOpen(event.currentTarget.checked)
                    }
                  />
                )} */}
            </div>
          </div>
          {/* {previewData && previewData.txCount === 0 && (
              <Alert severity={Severity.Clear} className={style.newAddressAlert}>
                {previewData.checksum === false
                  ? t('withdrawal.desc.newAndUnchecksummedAddressWarning')
                  : t('withdrawal.desc.newAddressWarning')}
              </Alert>
            )}
            {previewData && previewData.txCount > 0 && previewData.checksum === false && (
              <Alert severity={Severity.Clear} className={style.newAddressAlert}>
                {t('withdrawal.desc.unchecksummedAddressWarning')}
              </Alert>
            )} */}
          <div>
            <Button
              appearance="text"
              type="button"
              className={style.addressManagementButton}
              onClick={() =>
                navigate(Page.AddressManagement)
              }
            >
              地址管理
              <img src={IcForward} />
            </Button>
          </div>
          <div className={style.amountBlock}>
            <FormNumberInput
              name="amount"
              label="数量"
              placeholder="收到数量"
              hint={
                accountInfo === undefined
                  ? `${"可用余额"}: -`
                  : `${"可用余额"}: ${accountInfo?.FCoin} ${"USDT"}`
              }
              decimal={coinDecimal}
              required
              asterisked
            />
            <Button
              appearance="text"
              className={style.maxButton}
              type="button"
              disabled={accountInfo?.FCoin === undefined}
              onClick={() => {
                if (!accountInfo?.FCoin) return;
                methods.setValue('amount', bnFixed(accountInfo?.FCoin));
              }}
            >
              最大
            </Button>
          </div>
          <FormInput
            name="note"
            label="备忘"
            maxLength={64}
            hint="备忘不得超过 64 字"
            defaultValue={query.note}
          />
          <FormInput label="二步骤验证码" name="code" required asterisked />
          <div className={style.feeBlock}>
            <div>手续费</div>
            <div className={style.feeAmount}>
              {baseDataInfo === undefined
                ? `-`
                : `${baseDataInfo.FSxf} ${"USDT"}`}
            </div>
          </div>
        </div>
        <div className={style.noticeBlock}>
          <div className={style.noticeHeading}>注意</div>
          <ul>
            <li className={style.noticeItems}>
              请确认自己的装置与浏览器的安全性，同时确认资料未遭到窜改或外泄。
            </li>
            <li className={style.noticeItems}>
              您的提领操作一旦完成，对应的资产所有权将由您变更为目标地址所对应的账户所有人享有，请您务必在提领操作前，仔细核对提领地址信息，确保提领属于自愿行为，并确认不涉及任何非法集资、诈骗等违法情形，谨防上当受骗，避免造成不必要的财产损失。
            </li>
          </ul>
        </div>
        <div className={style.submitButton}>
          <Button
            size="large"
            type="submit"
            disabled={
              !isDisable || Object.keys(methods.formState.errors).length !== 0
            }
          >
            送出
          </Button>
        </div>
      </Form>
      {/* <NewAddressModal
        open={isSaveAddressModalOpen}
        handleClose={() => setSaveAddressModalOpen(false)}
        coin={methods.getValues('coin')}
        network={methods.getValues('network')}
        address={methods.getValues('address')}
        onFinish={() => setRefresh(!refresh)}
      /> */}
      {/* <VerifyModal
        open={verifyModalOpen}
        onClose={() => setVerifyModalOpen(false)}
        withdrawalData={withdrawalData}
      /> */}
    </div>
  );
};

export default Withdrawal;
